
#include "CloudDuplicate.h"
#include "Duplicate/DuplicateMgr.h"
#include "Common/TableData/MonsterMonsterCfg.h"
#include "Character/HuoYueDuPart.h"
#include "Character/CreatureMgr.h"
CloudDuplicate::CloudDuplicate()
{
	m_byType = (int8_t)EDuplicateType::EDuplicateType_Cloud;
	m_dismiss = false;
	m_mapCharScore.clear();
	m_totalScore = 0;
	m_notifyScore = false;

	m_totalBossScore = 0;
	m_totalNormalScore = 0;
	m_totalKillBoss = 0;
	m_totalKillNormal = 0;

	m_mapCharKillBoss.clear();
	m_mapCharBossScore.clear();
	m_mapCharKillNormal.clear();
	m_mapCharNormalScore.clear();

	m_leftsec = 0;
	m_leftsecScore = 0;
}

CloudDuplicate::~CloudDuplicate()
{

}

//初始化
bool CloudDuplicate::Init(uint32_t nDuplicateID, uint32_t nSceneID, IBrushMonster *pBrush)
{
	return Duplicate::Init(nDuplicateID, nSceneID, pBrush);
}
//
void CloudDuplicate::UnInit()
{
	Duplicate::UnInit();
	m_dismiss = false;
	m_mapCharScore.clear();
	m_totalScore = 0;
	m_notifyScore = false;

	m_totalBossScore = 0;
	m_totalNormalScore = 0;

	m_mapCharKillBoss.clear();
	m_mapCharBossScore.clear();
	m_mapCharKillNormal.clear();
	m_mapCharNormalScore.clear();

	m_leftsec = 0;
	m_leftsecScore = 0;

}
//工会精英平均等级
int32_t CloudDuplicate::UnionAverageLev()
{
	return m_paramEx.unionAverageLev;
}

//积分怪物死亡
void CloudDuplicate::ScoreMonsDie(uint32_t monsId, int32_t count,int8_t byBoss, uint64_t killerCid)
{
	const MonsterMonsterCfgInfo *pMonsterCfg = g_GetMonsterMonsterCfgTable()->GetMonsterMonsterCfgInfo(monsId);
	if (nullptr == pMonsterCfg)
	{
		return;
	}
	if (nullptr == GetPlayer(killerCid))
	{
		return;
	}
	//每个怪物都将被赋予一定的分值，普通怪物分值=1*该怪物所在层数，BOSS分值=20*该BOSS所在层数；					
	int32_t score = 0;
	int32_t layer = m_pBrushMonster->CurLayer();
	if (byBoss)
	{
		layer -= 1;//boss死亡之后，刷怪那边默认会刷下一层的，当前层数会变成下一层，所以这里需要处理下
		layer = layer < 1 ? 1 : layer;

		score = 20 * layer;
	}
	else
	{
		score = 1 * layer;
	}

	UpdateScore(killerCid, pMonsterCfg->monsterType,count, score);
}
//活动状态
void CloudDuplicate::ActivityState(uint32_t actId, int32_t state, SUnionActParam &param)
{
	_UNUSE(actId);
	_UNUSE(param);
	//结束
	if (!state)
	{
		if (!m_bEnd)
		{
			m_bEnd = true;
			m_nResult = RET_FAIL;

			//转到完成状态
			SetDuplicateState((int8_t)EDuplicateState::EDuplicateState_Finish);
		}
	}
}
//生物进入场景
void CloudDuplicate::OnCreatureEnter(Creature *pCreature)
{
	if (CREATURE_PLAYER == pCreature->CreatureKind())
	{
		//增加活跃度		HuoYueDuPart* pHuoYueDuPart = dynamic_cast<HuoYueDuPart*>(pCreature->GetPart(PART_HUOYUEDU));		if (nullptr != pHuoYueDuPart)		{			//增加活跃度			pHuoYueDuPart->AddHuoYueDuRecord(HYDT_ACTIVITY_CLOUD);		}
	}
}


//是否能进入
bool CloudDuplicate::OnCanEnter(Creature *pCreature)
{
	_UNUSE(pCreature);
	return true;
}

//进入区域
bool CloudDuplicate::OnEnterArea(uint32_t nAreaID)
{
	_UNUSE(nAreaID);
	return true;
}
//复活
void CloudDuplicate::OnRelive(Player *pPlayer, int8_t byType)
{
	_UNUSE(pPlayer);
	_UNUSE(byType);
}
//主动离开副本之前 的处理 
void CloudDuplicate::OnActiveBeforeLeave(CharIDType cid)
{
	_UNUSE(cid);
	
}

//工会解散
void CloudDuplicate::UnionDismiss()
{
	m_dismiss = true;
	LogDebugFmtPrint("[logic] CloudDuplicate::UnionDismiss......dupid:%u, sceneid:%u, mapid:%u, unionid:%u,  ", m_nDuplicateID, m_nSceneID, m_nMapID, (uint32_t)m_paramEx.keyValue);
	if (!m_bEnd)
	{
		
		m_bEnd = true;
		m_nResult = RET_FAIL;

		//踢出玩家
		SET_UINT64 setPlayer = m_setPlayer;
		SET_UINT64::iterator iter = setPlayer.begin();
		for (; iter != setPlayer.end(); ++iter)
		{
			CharIDType charId = (*iter);
			Player *pPlayer = GetPlayer(charId);
			if (nullptr != pPlayer)
			{
				if (!LeaveDuplicate(pPlayer))
				{
					LogErrFmtPrint("[logic] CloudDuplicate::UnionDismiss....LeaveDuplicate failed....dupid:%u, sceneid:%u, mapid:%u, unionid:%u,  ", m_nDuplicateID, m_nSceneID, m_nMapID, (uint32_t)m_paramEx.keyValue);
				}
			}
		}

		//设置清理状态
		SetDuplicateState((int8_t)EDuplicateState::EDuplicateState_Clean);
	}
}
//踢出玩家
void CloudDuplicate::KickPlayer(CharIDType charId)
{
	Player *pPlayer = GetPlayer(charId);
	if (nullptr != pPlayer)
	{
		LogDebugFmtPrint("[logic] CloudDuplicate::KickPlayer......dupid:%u, sceneid:%u, mapid:%u, unionid:%u, charid:%llu ", m_nDuplicateID, m_nSceneID, m_nMapID, (uint32_t)m_paramEx.keyValue, charId);
		if (!LeaveDuplicate(pPlayer))
		{
			LogErrFmtPrint("[logic] CloudDuplicate::KickPlayer....LeaveDuplicate failed....charid:%llu, dupid:%u, sceneid:%u, mapid:%u, unionid:%u,  ", charId, m_nDuplicateID, m_nSceneID, m_nMapID, (uint32_t)m_paramEx.keyValue);
		}
	}
}

//定时器更新
void CloudDuplicate::OnTimerUpdate(uint32_t nTimerID)
{
	switch (nTimerID)
	{
	case ETimer_Clean:
		{
			OnCommon_CleanStateEnd();
		}
		break;
	case ETimer_Destory:
		{
			LogDebugFmtPrint("[logic] CloudDuplicate destory .... duplicateid:%u , sceneid:%u, mapid:%u ", m_nDuplicateID, m_nSceneID, m_nMapID);
			//回收
			OnCommon_DestoryStateEnd();
		}
		break;
	case ETimer_Update:
		{
			if ((int32_t)EDuplicateState::EDuplicateState_Begin == GetDuplicateState())
			{
				if (!m_bEnd && GetMonsterNum() <= 0) //副本开始状态，检查是否完成
				{
					//怪物全部死亡，完成

					m_bEnd = true;
					m_nResult = RET_SUCCESS;

					//撞到完成状态
					SetDuplicateState((int8_t)EDuplicateState::EDuplicateState_Finish);
				}
				
				
			}
		}
		break;
	default:
		break;
	}
}
//执行事件
void CloudDuplicate::OnExecuteEvent(uint16_t nEventID, uint32_t nSrcID, uint8_t bySrcType, void *pContext, int32_t nLen)
{
	switch (nEventID)
	{
	case EVENT_CREATURE_DEAD:
	{
		/*if (CREATURE_MONSTER == bySrcType)
		{
			DieEvent *pDieEvent = (DieEvent*)pContext;
			if (pDieEvent->sceneId != m_nSceneID)
			{
				return;
			}
			const MonsterMonsterCfgInfo *pMonsterCfg = g_GetMonsterMonsterCfgTable()->GetMonsterMonsterCfgInfo(pDieEvent->monsterId);
			if (nullptr != pMonsterCfg)
			{
				if (nullptr == GetPlayer(pDieEvent->killerCid))
				{
					return;
				}
				//每个怪物都将被赋予一定的分值，普通怪物分值=1*该怪物所在层数，BOSS分值=20*该BOSS所在层数；					
				int32_t score = 0;
				int32_t layer = m_pBrushMonster->CurLayer();
				int8_t byBoss = 0;
				if (m_pBrushMonster->ValidMons(pDieEvent->nCid,byBoss))
				{
					if (byBoss)
					{
						layer -= 1;//boss死亡之后，刷怪那边默认会刷下一层的，当前层数会变成下一层，所以这里需要处理下
						layer = layer < 1 ? 1 : layer;

						score = 20 * layer;
					}
					else
					{
						score = 1 * layer;
					}

					if (pDieEvent->killerCid > 0)
					{
						UpdateScore(pDieEvent->killerCid, pMonsterCfg->monsterType, pDieEvent->count, score);
					}
				}
					
			}
		}*/

	}
	break;
	case EVENT_ENTER_SCENE:
	{
	}
	break;
	case EVENT_DISCONNECT:
	{
	}
	break;
	}
}

//生物离开副本
void CloudDuplicate::PlayerLeave(CharIDType cid)
{
	if (!OnCommon_PlayerLeave(cid))
	{
		LogErrFmtPrint("[logic] CloudDuplicate::PlayerLeave....return false ....duplicateid:%u, sceneid:%u , cid%lu ", m_nDuplicateID, m_nSceneID, cid);
		return;
	}
}

//通知玩家副本完成
void CloudDuplicate::OnNotifyFinish(CharIDType charId, DuplicateResult &result)
{
	result.nResult = RET_SUCCESS;//云端试炼副本没有失败的情况
	result.unionScore = m_totalScore;
	result.unionNormalScore = m_totalNormalScore;
	result.unionNormalNum = m_totalKillNormal;
	result.unionBossScore = m_totalBossScore;
	result.unionBossNum = m_totalKillBoss;

	result.leftsec = m_leftsec;
	result.leftsecScore = m_leftsecScore;

	result.charScore = CharScore(charId);
	result.charBossNum = CharKillBossNum(charId);
	result.charBossScore = CharBossScore(charId);
	result.charNormalNum = CharKillNormalNum(charId);
	result.charNormalScore = CharNormalScroe(charId);

	LogDebugFmtPrint("[logic] CloudDuplicate::OnNotifyFinish.....dupid:%u, sceneid:%u, cid:%lu, charScore:%d, charBossNum:%d, charBossScore:%d, charNormalNum:%d,charNormalScore:%d  ", m_nDuplicateID, m_nSceneID,charId, result.charScore, result.charBossNum, result.charBossScore, result.charNormalNum, result.charNormalScore);
}


void CloudDuplicate::OnReady_State()
{

}

void CloudDuplicate::OnBegin_State()
{
	OnCommon_DupBeginState();
}

void CloudDuplicate::OnFinish_State()
{
	//计算剩余时间得分
	CalcLeftSecScore();
	if (!m_notifyScore)
	{
		m_notifyScore = true;
		//通知中心服工会 玩家分数
		if (!m_dismiss)
		{
			LogDebugFmtPrint("[logic] CloudDuplicate::OnFinish_State.... dupid:%u, sceneid:%u, unionid:%u, total:%lu,total_normal:%d, total_boss:%d,left_time_score:%d,leftime:%d ", m_nDuplicateID, m_nSceneID, (uint32_t)m_paramEx.keyValue, m_totalScore, m_totalNormalScore, m_totalBossScore,m_leftsecScore,m_leftsec);
			//通关
			SyncAddScore(1, 0,0,m_leftsecScore); //这里只是通知中心服云端试练已通关，所以玩家CID为0,增加的积分也为0，

			/*LC_UnionScoreRsp rsp;
			rsp.set_union_id((uint32_t)m_paramEx.keyValue);
			rsp.set_union_score(m_totalScore);
			UnionAllCloudScoreProto *allProto = rsp.mutable_cloud();
			MAP_UINT64_INT32::iterator iter = m_mapCharScore.begin();
			for (; iter != m_mapCharScore.end(); ++iter)
			{
				LogDebugFmtPrint("[logic] CloudDuplicate::OnFinish_State.... dupid:%u, sceneid:%u, unionid:%u, charid:%lu, score:%u ", m_nDuplicateID, m_nSceneID, (uint32_t)m_paramEx.keyValue, iter->first, iter->second);
				UnionCloudScoreProto *proto = allProto->add_score();
				if (nullptr != proto)
				{
					proto->set_charid(iter->first);
					proto->set_score(iter->second);
				}
			}
			g_GetLogicService()->SendDataToCenter(EMODULE_ID_UNION, LOGIC_TO_CENTER_UNION_SCORE_RSP, &rsp);*/
		}
	}

	//
	OnCommon_DupFinishState();
}

void CloudDuplicate::OnFlop_State()
{
	//设置抽奖时间 15s
	LogDebugFmtPrint("[logic] CloudDuplicate::OnDuplicateState_Flop....duplicateid:%u , sceneid:%u ", m_nDuplicateID, m_nSceneID);
	//OnCommon_DupFlopState();
}

void CloudDuplicate::OnClean_State()
{
	OnCommon_DupCleanState();
}

void CloudDuplicate::OnDestory_State()
{
	OnCommon_DupDestoryState();
}
//更新分数
void CloudDuplicate::UpdateScore(CharIDType cid, int32_t monsType, int32_t count, int32_t score)
{
	LogDebugFmtPrint("[logic] CloudDuplicate::UpdateScore....cid:%lu, monsType:%d, count:%d ,score:%d ",cid,monsType,count,score);
	//玩家总积分
	MAP_UINT64_INT32::iterator iter = m_mapCharScore.find(cid);
	if (iter != m_mapCharScore.end())
	{
		iter->second += score;
	}
	else
	{
		m_mapCharScore[cid] = score;
	}
	//工会总积分
	m_totalScore += score;

	if (ENUM_MONSTER_TYPE_BOSS_MONSTER == monsType) //boss
	{
		m_totalBossScore += score; //工会boss积分
		m_totalKillBoss += count;
		//玩家boss积分
		MAP_UINT64_INT32::iterator iterBoss = m_mapCharBossScore.find(cid);
		if (iterBoss != m_mapCharBossScore.end())
		{
			iterBoss->second += score;
		}
		else
		{
			m_mapCharBossScore[cid] = score;
		}
		//玩家boss数量
		MAP_UINT64_INT32::iterator iterKill = m_mapCharKillBoss.find(cid);
		if (iterKill != m_mapCharKillBoss.end())
		{
			iterKill->second += count;
		}
		else
		{
			m_mapCharKillBoss[cid] = count;
		}

	}
	else
	{
		m_totalNormalScore += score; //工会小怪积分
		m_totalKillNormal += count;

		//玩家小怪积分
		MAP_UINT64_INT32::iterator iterNormal = m_mapCharNormalScore.find(cid);
		if (iterNormal != m_mapCharNormalScore.end())
		{
			iterNormal->second += score;
		}
		else
		{
			m_mapCharNormalScore[cid] = score;
		}
		//玩家小怪数量
		MAP_UINT64_INT32::iterator iterKill = m_mapCharKillNormal.find(cid);
		if (iterKill != m_mapCharKillNormal.end())
		{
			iterKill->second += count;
		}
		else
		{
			m_mapCharKillNormal[cid] = count;
		}
	}
	SyncAddScore(0, cid, score);
}

//同步分数到中心服
void CloudDuplicate::SyncAddScore(int32_t pass, CharIDType cid, int32_t addScore, int32_t leftTimeScore /*= 0*/)
{
	LC_UnionScoreRsp rsp;
	rsp.set_union_id((uint32_t)m_paramEx.keyValue);
	rsp.set_union_score(addScore + leftTimeScore);
	rsp.set_pass(pass);
	UnionAllCloudScoreProto *allProto = rsp.mutable_cloud();
	if (cid > 0)
	{
		UnionCloudScoreProto *proto = allProto->add_score();
		if (nullptr != proto)
		{
			proto->set_charid(cid);
			proto->set_score(addScore);
		}
	}
	g_GetLogicService()->SendDataToCenter(EMODULE_ID_UNION, LOGIC_TO_CENTER_UNION_SCORE_RSP, &rsp);
}
//删除玩家积分
void CloudDuplicate::DelCharScore(CharIDType charId)
{
	m_mapCharScore.erase(charId);
	m_mapCharKillBoss.erase(charId);
	m_mapCharKillNormal.erase(charId);
	m_mapCharBossScore.erase(charId);
	m_mapCharNormalScore.erase(charId);
}

int32_t CloudDuplicate::CharKillBossNum(CharIDType charId)
{
	MAP_UINT64_INT32::iterator iter = m_mapCharKillBoss.find(charId);
	return (iter != m_mapCharKillBoss.end()) ? iter->second : 0;
}

int32_t CloudDuplicate::CharKillNormalNum(CharIDType charId)
{
	MAP_UINT64_INT32::iterator iter = m_mapCharKillNormal.find(charId);
	return (iter != m_mapCharKillNormal.end()) ? iter->second : 0;
}

int32_t CloudDuplicate::CharBossScore(CharIDType charId)
{
	MAP_UINT64_INT32::iterator iter = m_mapCharBossScore.find(charId);
	return (iter != m_mapCharBossScore.end()) ? iter->second : 0;
}

int32_t CloudDuplicate::CharNormalScroe(CharIDType charId)
{
	MAP_UINT64_INT32::iterator iter = m_mapCharNormalScore.find(charId);
	return (iter != m_mapCharNormalScore.end()) ? iter->second : 0;
}

int32_t CloudDuplicate::CharScore(CharIDType charId)
{
	MAP_UINT64_INT32::iterator iter = m_mapCharScore.find(charId);
	return (iter != m_mapCharScore.end()) ? iter->second : 0;
}

void CloudDuplicate::CalcLeftSecScore()
{
	int32_t lefsec = 0;
	uint64_t curTime = g_GetGlobalServerTime()->UnixSec();
	if (curTime < m_paramEx.endTime)
	{
		lefsec = m_paramEx.endTime - curTime;
	}
	//同时活动时间也将被赋予分值，每1秒钟等于1分，公会通关副本后剩余的活动时间将会被计算为时间分；
	m_leftsecScore = 1 * lefsec;
	m_leftsec = lefsec;

	//剩余时间分数最后加到工会总分上
	m_totalScore += m_leftsecScore;
}